<?php
namespace Common\Action;
use Think\Action;
class FuncAction extends Action
{
	
protected function receipt(){
$ComputingTime = abs(C('yh_ComputingTime'))*86400;
$now=NOW_TIME;
$usermod = M('user');
$ordermod = M('order');
$cashmod = M('usercash');
$where['_string']='('.($now-$ComputingTime).'>up_time and status = 3 and settle = 0) and (uid>0 or fuid is not null or guid is not null or relation_id is not null)';
$field ='id,uid,fuid,guid,income,leve1,leve2,leve3,up_time,orderid,relation_id,
(select fuid from tqk_user where tqk_order.relation_id = tqk_user.webmaster_pid and tqk_order.relation_id >0 limit 1 ) as userid_fuid,
(select guid from tqk_user where tqk_order.relation_id = tqk_user.webmaster_pid and tqk_order.relation_id >0 limit 1 ) as userid_guid,
(select id from tqk_user where tqk_order.relation_id = tqk_user.webmaster_pid and tqk_order.relation_id >0 limit 1 ) as userid_f';
$list=$ordermod->field($field)->where($where)->limit(100)->select();
if($list){
$count =0;
foreach($list as $k=>$v){
	
	if($v['relation_id']){
	
	 $this->SettleRelation($v,$usermod,$ordermod,$cashmod);
		
	}else{
	
	 $this->SettleUser($v,$usermod,$ordermod,$cashmod);
		
	}
$count ++;
		
}

return $count;
		
}

return false;

}

protected function SettleUser($item,$usermod,$ordermod,$cashmod){
	
  if($item['uid'] && $item['uid']>0){
	    $money = Orebate1(array('price'=>$item['income'],'leve'=>$item['leve1']));
		$datacash=array(
		'create_time'=>NOW_TIME,
		'money'=>$money,
		'remark'=>'订单'.$item['orderid'],
		'status'=>1,
		'uid'=>$item['uid'],
		'type'=>3
		);
	$ret=$cashmod->add($datacash);
		if($money>0){
		$usermod->where(array('id'=>$item['uid']))->setInc('money',$money);
		}
	}

  if($item['fuid'] && $item['fuid']>0){
	    $money2 = Orebate2(array('price'=>$item['income'],'leve'=>$item['leve2']));
		$datacash2=array(
		'create_time'=>NOW_TIME,
		'money'=>$money2,
		'remark'=>'订单'.$item['orderid'],
		'status'=>1,
		'uid'=>$item['fuid'],
		'type'=>3
		);
	   $ret=$cashmod->add($datacash2);
		if($money2>0){
		$usermod->where(array('id'=>$item['fuid']))->setInc('money',$money2);
		}
	}
	
	
  if($item['guid'] && $item['guid']>0){
	    $money3 = Orebate2(array('price'=>$item['income'],'leve'=>$item['leve3']));
		$datacash3=array(
		'create_time'=>NOW_TIME,
		'money'=>$money3,
		'remark'=>'订单'.$item['orderid'],
		'status'=>1,
		'uid'=>$item['guid'],
		'type'=>3
		);
	   $ret=$cashmod->add($datacash3);
		if($money2>0){
		$usermod->where(array('id'=>$item['guid']))->setInc('money',$money3);
		}
	}
	
	
	
$ordermod->where(array('id'=>$item['id']))->setField('settle',1);
	
}


protected function SettleRelation($item,$usermod,$ordermod,$cashmod){
$money = round($item['income']*($item['leve1']/100),2);
$datacash=array(
		'create_time'=>NOW_TIME,
		'money'=>$money,
		'remark'=>'订单'.$item['orderid'],
		'status'=>1,
		'uid'=>$item['userid_f'],
		'type'=>3
		);

	$ret=$cashmod->add($datacash);
	if($money>0){
	$usermod->where(array('id'=>$item['userid_f']))->setInc('money',$money);
	}
	
  if($item['userid_fuid'] && $item['userid_fuid']>0){
	    $money2 = Orebate2(array('price'=>$item['income'],'leve'=>$item['leve2']));
		$datacash2=array(
		'create_time'=>NOW_TIME,
		'money'=>$money2,
		'remark'=>'订单'.$item['orderid'],
		'status'=>1,
		'uid'=>$item['userid_fuid'],
		'type'=>3
		);
	   $ret=$cashmod->add($datacash2);
		if($money2>0){
		$usermod->where(array('id'=>$item['userid_fuid']))->setInc('money',$money2);
		}
	}
	
	
	  if($item['userid_guid'] && $item['userid_guid']>0){
	    $money3 = Orebate2(array('price'=>$item['income'],'leve'=>$item['leve3']));
		$datacash3=array(
		'create_time'=>NOW_TIME,
		'money'=>$money3,
		'remark'=>'订单'.$item['orderid'],
		'status'=>1,
		'uid'=>$item['userid_guid'],
		'type'=>3
		);
	   $ret=$cashmod->add($datacash3);
		if($money3>0){
		$usermod->where(array('id'=>$item['userid_guid']))->setInc('money',$money3);
		}
	}
	
	
	
	$ordermod->where(array('id'=>$item['id']))->setField('settle',1);
}
	
	/**
     * 添加邮件到队列
     */
    protected function _mail_queue($to, $subject, $body, $priority = 1) {
        $to_emails = is_array($to) ? $to : array($to);
        $mails = array();
        $time = time();
        foreach ($to_emails as $_email) {
            $mails[] = array(
                'mail_to' => $_email,
                'mail_subject' => $subject,
                'mail_body' => $body,
                'priority' => $priority,
                'add_time' => $time,
                'lock_expiry' => $time,
            );
        }
        M('mail_queue')->addAll($mails);
        //异步发送邮件
        $this->send_mail(true);
    }


protected function send_sms($data=array()){
$appid=trim(C('yh_sms_appid'));
$appkey=trim(C('yh_sms_appkey'));
$smsSign=trim(C('yh_sms_sign'));
$phoneNumbers = [$data['phone']];
try {
    $ssender = new \Common\Tqklib\sms\SmsSingleSender($appid, $appkey);
    if($data['webname']){
    $params = [$data['code'],$data['webname']];
    }else{
    	$params = [$data['code']];
    }
    $result = $ssender->sendWithParam("86", $phoneNumbers[0], $data['temp_id'],
        $params, $smsSign, "", "");  // 签名参数未提供或者为空时，会使用默认签名发送短信
    $rsp = json_decode($result);
    return $result;
} catch(\Exception $e) {
    return false;
}
	
}


    public function send_mail($is_sync = true) {
        if (!$is_sync) {
            //异步
            session('async_sendmail', true);
            return true;
        } else {
            //同步
            session('async_sendmail', null);
            return D('mail_queue')->send();
        }
    }

    protected function _upload_init($upload) {
        $allow_max = C('yh_attr_allow_size'); //读取配置
        $allow_exts = explode(',', C('yh_attr_allow_exts')); //读取配置
        $allow_max && $upload->maxSize = $allow_max * 1024;   //文件大小限制
        $allow_exts && $upload->allowExts = $allow_exts;  //文件类型限制
        $upload->saveRule = 'uniqid';
        return $upload;
    }

    /**
     * 上传文件
     */
    protected function _upload_old($file, $dir = '', $thumb = array(), $save_rule='uniqid') {
      
        $upload = new UploadFile();
        if ($dir) {
            $upload_path = C('yh_attach_path') . $dir . '/';
            $upload->savePath = $upload_path;
        }
        if ($thumb) {
            $upload->thumb = true;
            $upload->thumbMaxWidth = $thumb['width'];
            $upload->thumbMaxHeight = $thumb['height'];
            $upload->thumbPrefix = '';
            $upload->thumbSuffix = isset($thumb['suffix']) ? $thumb['suffix'] : '_thumb';
            $upload->thumbExt = isset($thumb['ext']) ? $thumb['ext'] : '';
            $upload->thumbRemoveOrigin = isset($thumb['remove_origin']) ? true : false;
        }

        //自定义上传规则
        $upload = $this->_upload_init($upload);
        if( $save_rule!='uniqid' ){
            $upload->saveRule = $save_rule;
        }

        if ($result = $upload->uploadOne($file)) {
            return array('error'=>0, 'info'=>$result);
        } else {
            return array('error'=>1, 'info'=>$upload->getErrorMsg());
        }
    }

	protected function str_mid_replace($string) {
		if (! $string || !isset($string[1])) return $string;
		$len = strlen($string);
		$starNum = floor($len / 2); 
		$noStarNum = $len - $starNum;
		$leftNum = ceil($noStarNum / 2); 
		$starPos = $leftNum;
		for($i=0; $i<$starNum; $i++) $string[$starPos+$i] = '*';

		return $string;
	}

protected function api_yh_publish_update($item)
    {
        $result = $this->api_yh_update_order($item);
		
        return $result;
    }
    
 protected function api_yh_publish_fail($item)
    {
        $result = $this->api_yh_fail_order($item);
		
        return $result;
    }

protected function api_yh_fail_order($item) {
	$prefix = C(DB_PREFIX);
	$table=$prefix.'order';
	$sql='select id,uid,integral,nstatus from '.$table.' where (status=1 or status=3) and orderid ="'.$item['orderid'].'"';
	$res=M()->query($sql);

 if ($item['status']==2 && $res){
	$map=array(
	'id'=>$res[0]['id']
	);
    	
	$data=array(
	'up_time'=>$item['up_time'],
	'status' =>2
	);
$result=M('order')->where($map)->save($data);
if($result){
	
if($res[0]['integral']>0 && $res[0]['nstatus']==0){
M('user')->where('id='.$res[0]['uid'])->save(array(
 'score'=>array('exp','score-'.$res[0]['integral'])
));
}
	
	return 1;
	}else{
	return 0;
	}
		
		
	}else{
			
		return 0;

        }
     
    }



protected function api_yh_update_order($item) {
	$prefix = C(DB_PREFIX);
	$table=$prefix.'order';
	//$sql='select id,uid,integral,nstatus from '.$table.' where (status=1 or status=2) and orderid ="'.$item['orderid'].'" and goods_iid="'.$item['goods_iid'].'" and format('.$table.'.price,2) = format('.$item['price'].',2)';
	$sql='select id,uid,integral,nstatus from '.$table.' where (status=1 or status=2) and orderid ="'.$item['orderid'].'"';
	$res=M()->query($sql);

 if ($item['status']==3 && $res){
	$map=array(
	'id'=>$res[0]['id']
	);
    	
	$data=array(
	'up_time'=>$item['up_time'],
	'status' =>3
	);
$result=M('order')->where($map)->save($data);
if($result){
$map=array(
'id'=>$res[0]['uid'],
'tbname'=>array('neq',1),
'webmaster'=>array('neq',1)
);
if($res[0]['integral']>0 && $res[0]['nstatus']==0){
M('user')->where($map)->save(array(
 'score'=>array('exp','score+'.$res[0]['integral'])
));
}
	return 1;
	}else{
	return 0;
	}
		
		
	}else{
			
		return 0;

        }
     
    }
    
    
  protected function _api_yh_publish_insert($item)
    {
        $result =$this->api_yh_publish_stat($item);
		
        return $result;
    }
    
    
     protected function _api_Scene_publish_insert($item)
    {
        $result =$this->api_Scene_publish_stat($item);
		
        return $result;
    }
    
 protected function api_Scene_publish_stat($item){
	$prefix = C(DB_PREFIX);
	 $table=$prefix.'order';
	 
	$field='fuid,guid,webmaster_rate,(select id from '.$table.' where  tqk_order.orderid ="'.$item['orderid'].'" limit 1) as nid';
	$ret=M('user')->field($field)->where(array('webmaster_pid'=>$item['relation_id']))->limit(1)->find();
	$mod=M('order');
	
if($ret){

if($ret['nid']<=0 && $item['status']==1){
	
	  $item['status']=1;
	  $item['nstatus']=2;
	  $data['fuid']=$ret['fuid'];
      $data['guid']=$ret['guid'];
	  $item['leve1']=$ret['webmaster_rate'];
	  $item['oid']=md5($item['oid']);
	 $mod->create($item);
      $item_id = $mod->add();
      if ($item_id) {
            return 1;
        } else {
            return 0;
        }
	
}else{
$data['relation_id']	=$item['relation_id'];
$data['leve1']=$ret['webmaster_rate'];
$data['nstatus']=2;
$data['fuid']=$ret['fuid'];
$data['guid']=$ret['guid'];
$sqlwhere['orderid'] = $item['orderid'];
$res=$mod->where($sqlwhere)->save($data);
if ($res) {
            return 1;
        } else {
            return 0;
        }	
	
}

}

 return 0;

     
 }
    
    
 protected function api_yh_publish_stat($item){
	$prefix = C(DB_PREFIX);
	 $table=$prefix.'order';
	//$sql='select id from '.$table.' where status=1 and orderid ="'.$item['orderid'].'" and goods_iid="'.$item['goods_iid'].'" and format('.$table.'.price,2) = format('.$item['price'].',2)';
	$sql='select id from '.$table.' where  orderid ="'.$item['orderid'].'"';
	$num=M()->execute($sql);
	$mod=M('order');
if($num<=0 && $item['status']==1){
	
	  $item['status']=1;
	  $item['nstatus']=1;
	  $item['oid']=md5($item['oid']);
		$mod->create($item);
        $item_id = $mod->add();
        if ($item_id) {
            return 1;
        } else {
            return 0;
        }
	
}else{
	
	return 0;
	
}

     
    }
 
    protected function ajaxReturn($status=1, $msg='', $data='', $dialog='') {
        parent::ajaxReturn(array(
            'status' => $status,
            'msg' => $msg,
            'data' => $data,
            'dialog' => $dialog,
        ));
    }

	protected function jsonReturn($data,$type='JSON'){
    	header('Content-Type:application/json; charset=utf-8');
    	exit(json_encode($data));
    }
}